/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.app.rest.runtime;

import cmbchina.util.AjaxJson;
import cmbchina.util.FlowScriptRunUtils;
import cmbchina.util.RunScript;
import cmbchina.util.ScriptResult;
import cmbchina.util.db.FlowFormDb;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.flowable.app.model.runtime.CompleteFormRepresentation;
import org.flowable.app.model.runtime.ProcessInstanceVariableRepresentation;
import org.flowable.app.service.runtime.FlowableTaskFormService;
import org.flowable.content.api.ContentManagementService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.ManagementServiceImpl;
import org.flowable.engine.impl.TaskServiceImpl;
import org.flowable.form.api.FormService;
import org.flowable.form.model.FormModel;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Joram Barrez
 */
@RestController
@RequestMapping("/rest/task-forms")
public class TaskFormResource {

    @Autowired
    protected FlowableTaskFormService taskFormService;
    @Autowired
    protected TaskServiceImpl taskService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected FormService formService;

    @RequestMapping(value = "/{taskId}", method = RequestMethod.GET, produces = "application/json")
    public FormModel getTaskForm(@PathVariable String taskId) {
        return taskFormService.getTaskForm(taskId);
    }



    @ResponseStatus(value = HttpStatus.OK)
    @RequestMapping(value = "/{taskId}", method = RequestMethod.POST, produces = "application/json")
    public AjaxJson completeTaskForm(@PathVariable String taskId, @RequestBody CompleteFormRepresentation completeTaskFormRepresentation) {
        System.out.println("test=======");
        FlowScriptRunUtils scriptRunUtils = new FlowScriptRunUtils();

        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        AjaxJson ajaxJson =new AjaxJson();
//        ajaxJson = RunScript.runScript(completeTaskFormRepresentation,taskService,task,task.getDescription());
//        taskFormService.completeTaskForm(taskId, completeTaskFormRepresentation);
        return ajaxJson;
    }

    @ResponseStatus(value = HttpStatus.OK)
    @RequestMapping(value = "/autoComplete/{queryProcessInstId}/{taskId}", method = RequestMethod.GET, produces = "application/json")
    public AjaxJson completeTaskFormAuto( @PathVariable String queryProcessInstId,@PathVariable String taskId) {
        System.out.println("autoComplete=======");
        AjaxJson ajaxJson = new AjaxJson();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String formInfo = FlowFormDb.queryFormInfo(task.getTaskDefinitionKey(), queryProcessInstId);
        if(null!=formInfo &&!"".equals(formInfo)){

            try{
                ObjectMapper obj = new ObjectMapper();
                Map<String,Object> map = obj.readValue(formInfo,Map.class);
                Map<String,Object> formInfoMap = (Map<String, Object>) map.get("formInfo");
                CompleteFormRepresentation completeTaskFormRepresentation = new CompleteFormRepresentation();
                completeTaskFormRepresentation.setFormId((String) formInfoMap.get("formId"));
                completeTaskFormRepresentation.setOutcome(formInfoMap.get("outcome")==null?null:formInfoMap.get("outcome").toString());
                completeTaskFormRepresentation.setValues((Map<String, Object>) formInfoMap.get("values"));
//                CompleteFormRepresentation completeTaskFormRepresentation = obj.readValue(map.get("formInfo"),CompleteFormRepresentation.class);
//                RunScript.runScript(completeTaskFormRepresentation,taskService,task,task.getDescription());
//                taskFormService.completeTaskForm(taskId,completeTaskFormRepresentation);
            }catch (Exception e){
                e.printStackTrace();
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(e.getMessage());
            }
        }
        else{
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("预配置参数查询失败！");
        }
        return ajaxJson;
    }


}
